/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package NetworkReceiver;

import FrameWork.Item;
import NetworkPackage.clientConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import javax.bluetooth.*;
import javax.microedition.io.*;
/**
 * this class is used to to wait for messages coming from the mobile clients and queuing them and notifing the messages observer
 * his class extends Thread because the listen function is running in a thread alone
 */
public class NetworkObserver extends Thread{
    Queue<String> msgQ = new ArrayBlockingQueue<String>(100);
    static NetworkObserver instance;
    NetworkObserver(){}
    public static NetworkObserver getInstance()
    {
        if(instance == null)
        {
            instance = new NetworkObserver();
        }
        return instance;
    }

    @Override
    public void run() {// this function is used to run a thread
        listen();
    }
    
    public void addXMLItem(String xml)  // this function is used add incoming item in XML format in the queue
    {
        msgQ.add(xml);
    }
    public String getXMLItem()          // this function is used to get XML item from the queue 
    {
        if(msgQ.isEmpty())
            return null;    // error
        return msgQ.remove();
    }
    // this function is used to get the incoming message from and adding it to the queue and uing the message observer to handle it
    public void _notify(StreamConnection strConn)   
    {
        String str = "";
        
        try
        {
            InputStream In = strConn.openInputStream();
            byte[]buff = new byte[1000];
            int n = In.read(buff);
            str = buff.toString();
        }
        catch(IOException ioex)
        {
            System.out.println(ioex.getMessage());
        }
                
        MessageObserver msgOb = MessageObserver.getInstance();
        Item item = msgOb.translate(str);
        item = msgOb.decryptItem(item);
        
        // i will put the connection in the sender id in the array
        if(item.getSenderID() < 100)
        {
            clientConnection.list[item.getSenderID()] = strConn;
        }
        msgOb.addItem(item);
    }
    public void listen()    // this function is running in thread and it's waiting for incoming connections
    {
        
        try
        {
            // let's name our variables

            StreamConnectionNotifier notifier = null;
            
            LocalDevice localdevice = LocalDevice.getLocalDevice();
            ServiceRecord servicerecord = null;
            InputStream input;
            OutputStream output;

            // let's create a URL that contains a UUID that 
            // has a very low chance of conflicting with anything
            String url = 
              "btspp://localhost:00112233445566778899AABBCCDDEEFF;name=serialconn";
            // let's open the connection with the url and
            // cast it into a StreamConnectionNotifier
            
            notifier = (StreamConnectionNotifier)Connector.open(url);
            while(true)
            {
                StreamConnection con = null;
                // block the current thread until a client responds
                System.out.println("before");
                con = notifier.acceptAndOpen();
                System.out.println("after");
                _notify(con);
                // the client has responded, so open some streams
               
            }
            // now that the streams are open, send and
            // receive some data
        }
        catch(IOException ioex)
        {
        System.out.println(ioex.getMessage());
        
        }
    
    }
}
